public with sharing class SetMonthSalesTargetControl{
    public List<User> allUserList{get;set;}
    private List<SalesTargetEntry> suplist;
    public Date d{get;set;}
    public Boolean IsDisplan{get;set;}
    public double iTotal1;
    public double iTotal2;
    public double iTotal3;
    public double iTotal4;
    public double iTotal5;
    public Boolean IsTotalDisplan{get;set;}
    public Map<Id,List<Sales_Target__c>> MapTsrTargetList;
    
    public List<SalesTargetEntry> supUserList
    {
        get
        {
                return suplist;
        }
        set
        {
                suplist=value;
        }
     }
    
    //public List<User> tsrUserList{get;set;}
    public Boolean userType{get;set;}
    public Sales_Target__c Starget{get;set;}
    public List<SalesTargetEntry> stEnList{get;set;}
   
    public SetMonthSalesTargetControl()
    {
        Starget=new Sales_Target__c();
        Starget.Year__c=String.valueOf(Date.today().year());//设置为当前年
        Starget.Month__c=String.valueOf(Date.today().month());//设置为当前月
       
        SetTarget();
    
    }
    public List<Sales_Target__c > TempTargetList{get;set;}
    public List<Sales_Target__c > SubTargetTotalList{get;set;}
    
    public void SetTarget()
    {
        IsTotalDisplan=true;
        User user=[select id,username,Name,Title__c,FunctionDepartment__c from User where id=:UserInfo.getUserId()];
        if(user.Title__c!=null)
        {
            //如果当前用户是Area/District Sales Manager或Sales Supervisor的时候找出它们的下级
            if((user.Title__c=='Area/District Sales Manager' || user.Title__c=='Sales Supervisor')&& (user.FunctionDepartment__c=='Trade Sales' || user.FunctionDepartment__c=='Trade&Medical Sales'))
            {
                userType=false;
                if(supUserList==null)
                    supUserList=new List<SalesTargetEntry>();
                else
                    supUserList.clear();
                
                //找出所有当前用户下的TSR ID列表
                Map<Id,User> MapTsrUserList=new Map<Id,User>([select id,username,name,title__c,FunctionDepartment__c 
                                                              from User where managerId=:user.Id and 
                                                              (Title__c='Sales Rep' and FunctionDepartment__c='Trade Sales')]);
                if(MapTsrTargetList==null)
                    MapTsrTargetList=new Map<Id,List<Sales_Target__c>>();
                else
                    MapTsrTargetList.clear();
                    
               for(Sales_Target__c tar:[select Id,Name,NextSales__c,Sales_Target_Type__c,SalesWeek1__c,SalesWeek2__c,
                                        SalesWeek3__c,SalesWeek4__c,SalesWeek5__c,TotalValue__c from Sales_Target__c 
                                        where OwnerId=:UserInfo.getUserId() and Year__C = :Starget.Year__c 
                                        and Month__c=:Starget.Month__c
                                        Order by CreatedDate])  
               {
                    if(!MapTsrTargetList.containsKey(tar.NextSales__c))
                    {
                        List<Sales_Target__c> tar1=new List<Sales_Target__c>();
                        tar1.add(tar);
                        MapTsrTargetList.put(tar.NextSales__c,tar1);
                    }
                    else
                    {
                        List<Sales_Target__c> tar2=MapTsrTargetList.get(tar.NextSales__c);
                        if(tar2!=NULL)
                        {
                            tar2.add(tar);
                            MapTsrTargetList.put(tar.NextSales__c,tar2);
                        }
                    }
                        
               }     
                //循环所有的下级列表
                for(User u:MapTsrUserList.values())
                {
                    if(u.Title__c=='Sales Rep' && u.FunctionDepartment__c=='Trade Sales' )//add TSR
                    {
                        if(Starget.Year__c!=null && Starget.Month__c!=null)
                        {
                            List<Sales_Target__c> l1=MapTsrTargetList.get(u.Id);
                            if(l1==null || l1.size()==0)
                            {
                                List<Sales_Target__c> tList=new List<Sales_Target__c>();
                                Sales_Target__c t=new Sales_Target__c();
                                t.NextSales__c=u.Id;
                                t.Sales_Target_Type__c='In-Market Sales(RMB)';
                                t.SalesWeek1__c=0;
                                t.SalesWeek2__c=0;
                                t.SalesWeek3__c=0;
                                t.SalesWeek4__c=0;
                                t.SalesWeek5__c=0;
                                t.year__c=Starget.year__c;
                                t.month__c=Starget.month__c;
                                t.Name=u.Name+t.year__c+t.month__c+'In-Market Sales(RMB';
                                
                                Sales_Target__c t5=new Sales_Target__c();
                                t5.NextSales__c=u.Id;
                                t5.Sales_Target_Type__c='Offtake (RMB)';
                                t5.SalesWeek1__c=0;
                                t5.SalesWeek2__c=0;
                                t5.SalesWeek3__c=0;
                                t5.SalesWeek4__c=0;
                                t5.SalesWeek5__c=0;
                                t5.year__c=Starget.year__c;
                                t5.month__c=Starget.month__c;
                                t5.Name=u.Name+t.year__c+t.month__c+'Offtake(RMB)';
                                
                                Sales_Target__c t2=new Sales_Target__c(); 
                                t2.NextSales__c=u.Id;
                                t2.Sales_Target_Type__c='Distributed Outlet Number';
                                t2.SalesWeek1__c=0;
                                t2.SalesWeek2__c=0;
                                t2.SalesWeek3__c=0;
                                t2.SalesWeek4__c=0;
                                t2.SalesWeek5__c=0;
                                t2.year__c=Starget.year__c;
                                t2.month__c=Starget.month__c;
                                t2.Name=u.Name+t.year__c+t.month__c+'Distributed Outlet Number';
                                
                                Sales_Target__c t3=new Sales_Target__c();
                                t3.NextSales__c=u.Id;
                                t3.Sales_Target_Type__c='Main-Shelf Standard Display Outlet Number';
                                t3.SalesWeek1__c=0;
                                t3.SalesWeek2__c=0;
                                t3.SalesWeek3__c=0;
                                t3.SalesWeek4__c=0;
                                t3.SalesWeek5__c=0;
                                t3.year__c=Starget.year__c;
                                t3.month__c=Starget.month__c;
                                t3.Name=u.Name+t.year__c+t.month__c+'Main-Shelf Standard Display Outlet Number';
                                
                                Sales_Target__c t4=new Sales_Target__c();
                                t4.NextSales__c=u.Id;
                                t4.Sales_Target_Type__c='SSY Activity Outlet Number';
                                t4.SalesWeek1__c=0;
                                t4.SalesWeek2__c=0;
                                t4.SalesWeek3__c=0;
                                t4.SalesWeek4__c=0;
                                t4.SalesWeek5__c=0;
                                t4.year__c=Starget.year__c;
                                t4.month__c=Starget.month__c;
                                t4.Name=u.Name+t.year__c+t.month__c+'SSY Activity Outlet Number';
                                
                                tList.add(t);
                                tList.add(t5);
                                tList.add(t2);
                                tList.add(t3);
                                tList.add(t4);
                                
                                SalesTargetEntry en=new SalesTargetEntry(tList,u);
                                supUserList.add(en);
                            }
                            else
                            {
                                //Order by List
                                List<Sales_Target__c> orderList=new List<Sales_Target__c>();
                                orderList=l1.clone();
                                for(Integer i=0;i<l1.size();i++)
                                {
                                    Sales_Target__c st=l1[i];
                                    if(st.Sales_Target_Type__c=='In-Market Sales(RMB)')
                                        orderList.set(0,st);
                                    else if(st.Sales_Target_Type__c=='Offtake (RMB)')
                                        orderList.set(1,st);
                                    else if(st.Sales_Target_Type__c=='Distributed Outlet Number')
                                        orderList.set(2,st);
                                    else if(st.Sales_Target_Type__c=='Main-Shelf Standard Display Outlet Number')
                                        orderList.set(3,st);
                                    else
                                        orderList.set(4,st); 
                                }
                                
                                SalesTargetEntry en=new SalesTargetEntry(orderList,u);
                                supUserList.add(en);
                            }
                        }
                    }
                }
            }
            else if(user.Title__c=='Sales Rep' && user.FunctionDepartment__c=='Trade Sales' )//如果是Sales Rep时从上级分配下来的Sales Target
            {
                userType=true;
                
                IsTotalDisplan=false;
                
                    if(supUserList==null)
                        supUserList=new List<SalesTargetEntry>();
                    else
                        supUserList.clear();
                    
                    List<Sales_Target__c> l1=[select Id,Name,NextSales__c,Sales_Target_Type__c,SalesWeek1__c,SalesWeek2__c,SalesWeek3__c,SalesWeek4__c,SalesWeek5__c,TotalValue__c from Sales_Target__c where Year__C = :Starget.Year__c and Month__c=:Starget.Month__c and NextSales__c=:user.Id];
                    SalesTargetEntry en=new SalesTargetEntry(l1,user);
                    supUserList.add(en);
                
            }
            else{}
            
            
            
            
            
            
                //如果是Area/District Sales Manager加载下级和下下级的Sales target,汇总
                if((user.Title__c=='Area/District Sales Manager' || user.Title__c=='Sales Supervisor')
                    && (user.FunctionDepartment__c=='Trade Sales' || user.FunctionDepartment__c=='Trade&Medical Sales'))
                {
                    stEnList=new List<SalesTargetEntry>();
                    List<Sales_Target__c> SalesList=new List<Sales_Target__c>();
                        
                    //SalesList=[Select TotalValue__c, Sales_Target_Type__c,NextSales__c,SalesWeek1__c,SalesWeek2__c,SalesWeek3__c,SalesWeek4__c,SalesWeek5__c From Sales_Target__c where Year__C = :Starget.Year__c and Month__c=:Starget.Month__c];
                    List<User> userList=new List<User>();
                   // List<User> userList=[select Id,Name from User where Id in(select NextSales__c from Sales_Target__c where Year__C = :Starget.Year__c and Month__c=:Starget.Month__c)];
                    
                    List<User> u1=[select Id,Name,Title__c,FunctionDepartment__c from User where managerId=:UserInfo.getUserId()];
                    set<Id> UserIdList=new Set<Id>();
                    for(User u:u1)
                    {
                        if(u.Title__c=='Sales Supervisor')
                        {
                              userList.add(u);
                              UserIdList.add(u.Id);
                        }
                    }
                    
                    for(User u:[select Id,Name,Title__c,FunctionDepartment__c 
                                    from User where managerId in: UserIdList and 
                                    Title__c='Sales Supervisor' and 
                                    (FunctionDepartment__c='Trade Sales' or FunctionDepartment__c='Trade&Medical Sales')])
                    {
                        if(!UserIdList.contains(u.Id))
                        {
                                userList.add(u);
                                UserIdList.add(u.Id);
                        }
                    }
                    
                    //汇总所有的sales target值
                    for(User ur:userList)
                    {
                        SalesList=[Select TotalValue__c, Sales_Target_Type__c,NextSales__c,SalesWeek1__c,SalesWeek2__c,
                                    SalesWeek3__c,SalesWeek4__c,SalesWeek5__c From Sales_Target__c 
                                    where Year__C = :Starget.Year__c and Month__c=:Starget.Month__c and OwnerId=:ur.Id];
                       
                        if(SalesList!=NULL && SalesList.size()>0)
                        {
                            List<Sales_Target__c> AsmStList=new List<Sales_Target__c>();
                            Sales_Target__c t=new Sales_Target__c();
                            t.Sales_Target_Type__c='In-Market Sales(RMB)';
                            t.SalesWeek1__c=0;
                            t.SalesWeek2__c=0;
                            t.SalesWeek3__c=0;
                            t.SalesWeek4__c=0;
                            t.SalesWeek5__c=0;
                                        
                            Sales_Target__c t5=new Sales_Target__c();
                            t5.Sales_Target_Type__c='Offtake (RMB)';
                            t5.SalesWeek1__c=0;
                            t5.SalesWeek2__c=0;
                            t5.SalesWeek3__c=0;
                            t5.SalesWeek4__c=0;
                            t5.SalesWeek5__c=0;
                                        
                            Sales_Target__c t2=new Sales_Target__c(); 
                            t2.Sales_Target_Type__c='Distributed Outlet Number';
                            t2.SalesWeek1__c=0;
                            t2.SalesWeek2__c=0;
                            t2.SalesWeek3__c=0;
                            t2.SalesWeek4__c=0;
                            t2.SalesWeek5__c=0;
                                        
                            Sales_Target__c t3=new Sales_Target__c();
                            t3.Sales_Target_Type__c='Main-Shelf Standard Display Outlet Number';
                            t3.SalesWeek1__c=0;
                            t3.SalesWeek2__c=0;
                            t3.SalesWeek3__c=0;
                            t3.SalesWeek4__c=0;
                            t3.SalesWeek5__c=0;
                                        
                            Sales_Target__c t4=new Sales_Target__c();
                            // t4.NextSales__c=u.Id;
                            t4.Sales_Target_Type__c='SSY Activity Outlet Number';
                            t4.SalesWeek1__c=0;
                            t4.SalesWeek2__c=0;
                            t4.SalesWeek3__c=0;
                            t4.SalesWeek4__c=0;
                            t4.SalesWeek5__c=0;
                                       
                            AsmStList.add(t);
                            AsmStList.add(t5);
                            AsmStList.add(t2);
                            AsmStList.add(t3);
                            AsmStList.add(t4);
        
                            double to1,to2,to3,to4,to5;
                                            
                            for(Sales_Target__c sst:SalesList)//DB query
                            {
                                for(Sales_Target__c sst2:AsmStList)
                                {
                                    if(sst2.Sales_Target_Type__c==sst.Sales_Target_Type__c)
                                    {
                                        sst2.SalesWeek1__c+=sst.SalesWeek1__c;
                                        sst2.SalesWeek2__c+=sst.SalesWeek2__c;
                                        sst2.SalesWeek3__c+=sst.SalesWeek3__c;
                                        sst2.SalesWeek4__c+=sst.SalesWeek4__c;
                                        sst2.SalesWeek5__c+=sst.SalesWeek5__c;
                                        
                                        if(sst2.Sales_Target_Type__c=='In-Market Sales(RMB)')
                                        {
                                                to1=sst2.SalesWeek1__c+sst2.SalesWeek2__c+sst2.SalesWeek3__c+sst2.SalesWeek4__c+sst2.SalesWeek5__c;
                                                sst2.Name=String.valueOf(to1.intValue());
                                        }
                                        else if(sst2.Sales_Target_Type__c=='Offtake (RMB)')
                                        {
                                                to2=sst2.SalesWeek1__c+sst2.SalesWeek2__c+sst2.SalesWeek3__c+sst2.SalesWeek4__c+sst2.SalesWeek5__c;
                                                sst2.Name=String.valueOf(to2.intValue());
                                        }
                                        else if(sst2.Sales_Target_Type__c=='Distributed Outlet Number')
                                        {
                                                to3=sst2.SalesWeek1__c+sst2.SalesWeek2__c+sst2.SalesWeek3__c+sst2.SalesWeek4__c+sst2.SalesWeek5__c;
                                                sst2.Name=String.valueOf(to3.intValue());
                                        }
                                        else if(sst2.Sales_Target_Type__c=='Main-Shelf Standard Display Outlet Number')
                                        {
                                                to4=sst2.SalesWeek1__c+sst2.SalesWeek2__c+sst2.SalesWeek3__c+sst2.SalesWeek4__c+sst2.SalesWeek5__c;
                                                sst2.Name=String.valueOf(to4.intValue());
                                        }
                                        else
                                        {
                                                to5=sst2.SalesWeek1__c+sst2.SalesWeek2__c+sst2.SalesWeek3__c+sst2.SalesWeek4__c+sst2.SalesWeek5__c;
                                                sst2.Name=String.valueOf(to5.intValue());
                                        }
                                    }
                                }
                            }
                                
                            SalesTargetEntry en=new SalesTargetEntry(AsmStList,ur);
                            stEnList.add(en);
                        }
                    }
                    if(stEnList.size()>0)
                        IsDisplan=true;
                    else
                        IsDisplan=false;
                }
                
                
                
                
                        
                        String year=Starget.year__c;
                        String month=Starget.Month__c;
                        Date d=Date.newInstance(Integer.valueof(year),Integer.valueof(month),1);//选择的日期
                        Integer Count=Date.toDay().monthsBetween(d);              
                        if(Count>0)
                        {
                            userType=false;
                        }
                        else
                                userType=true;
                
                 if(user.Title__c=='Sales Rep' && user.FunctionDepartment__c=='Trade Sales' )
                        userType=true;
            }
            
            
            
            //汇总数据
            TempTargetList=new List<Sales_Target__c>();
            Sales_Target__c t=new Sales_Target__c();
            t.Sales_Target_Type__c='In-Market Sales(RMB)';
            t.SalesWeek1__c=0;
            t.SalesWeek2__c=0;
            t.SalesWeek3__c=0;
            t.SalesWeek4__c=0;
            t.SalesWeek5__c=0;
                    
            Sales_Target__c t5=new Sales_Target__c();
            t5.Sales_Target_Type__c='Offtake (RMB)';
            t5.SalesWeek1__c=0;
            t5.SalesWeek2__c=0;
            t5.SalesWeek3__c=0;
            t5.SalesWeek4__c=0;
            t5.SalesWeek5__c=0;
                    
            Sales_Target__c t2=new Sales_Target__c(); 
            t2.Sales_Target_Type__c='Distributed Outlet Number';
            t2.SalesWeek1__c=0;
            t2.SalesWeek2__c=0;
            t2.SalesWeek3__c=0;
            t2.SalesWeek4__c=0;
            t2.SalesWeek5__c=0;
                    
            Sales_Target__c t3=new Sales_Target__c();
            t3.Sales_Target_Type__c='Main-Shelf Standard Display Outlet Number';
            t3.SalesWeek1__c=0;
            t3.SalesWeek2__c=0;
            t3.SalesWeek3__c=0;
            t3.SalesWeek4__c=0;
            t3.SalesWeek5__c=0;
                    
            Sales_Target__c t4=new Sales_Target__c();
            // t4.NextSales__c=u.Id;
            t4.Sales_Target_Type__c='SSY Activity Outlet Number';
            t4.SalesWeek1__c=0;
            t4.SalesWeek2__c=0;
            t4.SalesWeek3__c=0;
            t4.SalesWeek4__c=0;
            t4.SalesWeek5__c=0;
  
        //t4.Name=u.Name+t.year__c+t.month__c+'SSY Activity Outlet Number';
            
        TempTargetList.add(t);
        TempTargetList.add(t5);
        TempTargetList.add(t2);
        TempTargetList.add(t3);
        TempTargetList.add(t4);
      
      if(supUserList!=NULL || stEnList!=NULL)
       {
                List<SalesTargetEntry> AllSalesTargetList=new List<SalesTargetEntry>();
                for(SalesTargetEntry s1:supUserList)
                {
                        AllSalesTargetList.add(s1);
                }
                
                if(stEnList!=NULL)
                {
                        for(SalesTargetEntry s2:stEnList)
                        {
                                AllSalesTargetList.add(s2);
                        }
                }
               for(SalesTargetEntry se:AllSalesTargetList)
                {
                        for(Sales_Target__c st:se.tar)
                        {
                                for(Sales_Target__c s2:TempTargetList)
                                {
                                    if(st.Sales_Target_Type__c==s2.Sales_Target_Type__c)
                                    {
                                        s2.SalesWeek1__c+=st.SalesWeek1__c;
                                        s2.SalesWeek2__c+=st.SalesWeek2__c;
                                        s2.SalesWeek3__c+=st.SalesWeek3__c;
                                        s2.SalesWeek4__c+=st.SalesWeek4__c;
                                        s2.SalesWeek5__c+=st.SalesWeek5__c;
                
                                        if(st.Sales_Target_Type__c=='In-Market Sales(RMB)')
                                        {
                                            iTotal1=s2.SalesWeek1__c+s2.SalesWeek2__c+s2.SalesWeek3__c+s2.SalesWeek4__c+s2.SalesWeek5__c;
                                            s2.Name=String.valueOf(iTotal1.intValue());
                                        }
                                        else if(st.Sales_Target_Type__c=='Offtake (RMB)')
                                        {
                                            iTotal2=s2.SalesWeek1__c+s2.SalesWeek2__c+s2.SalesWeek3__c+s2.SalesWeek4__c+s2.SalesWeek5__c;
                                            s2.Name=String.valueOf(iTotal2.intValue());
                                        }
                                        else if(st.Sales_Target_Type__c=='Distributed Outlet Number')
                                        {
                                            iTotal3=s2.SalesWeek1__c+s2.SalesWeek2__c+s2.SalesWeek3__c+s2.SalesWeek4__c+s2.SalesWeek5__c;
                                            s2.Name=String.valueOf(iTotal3.intValue());
                                        }
                                        else if(st.Sales_Target_Type__c=='Main-Shelf Standard Display Outlet Number')
                                        {
                                            iTotal4=s2.SalesWeek1__c+s2.SalesWeek2__c+s2.SalesWeek3__c+s2.SalesWeek4__c+s2.SalesWeek5__c;
                                            s2.Name=String.valueOf(iTotal4.intValue());
                                        }
                                        else
                                        {
                                            iTotal5=s2.SalesWeek1__c+s2.SalesWeek2__c+s2.SalesWeek3__c+s2.SalesWeek4__c+s2.SalesWeek5__c;
                                            s2.Name=String.valueOf(iTotal5.intValue());
                                        }
                                    }
                                }
                        }
               }
        }
     
    }
    
    public PageReference Save()
    {
       if(supUserList!=null)
       {
           // List<Sales_Target__c> tar=new List<Sales_Target__c>();
            for(SalesTargetEntry en:supUserList)
           {
              upsert en.tar;
           }
           SetTarget();
          
       }
      
        return null;
    }
    
    public PageReference OnchageAction() {
        
        //Date.today()
        if(Starget.Month__c != NULL)
            SetTarget();
        return null;
    }
    
    static testmethod void Test()
    {
        SetMonthSalesTargetControl ss=new SetMonthSalesTargetControl();
        ss.Starget.Year__c='2010';
        ss.Starget.month__c='8';
        Profile p = [select id from profile where Name='System Administrator' or name = '系统管理员'];
        User u = new User(alias = 'standtss', email='standarduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,title__c='Area/District Sales Manager',FunctionDepartment__c='Trade Sales',
        timezonesidkey='America/Los_Angeles', username='standardusers@testorg.com');
        insert u;
        
         User u3 = new User(alias = 'test', email='dfffd@testorgss.com',
        emailencodingkey='UTF-8', lastname='Tfffting', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,title__c='Sales Supervisor',FunctionDepartment__c='Trade Sales',managerId=u.Id,
        timezonesidkey='America/Los_Angeles', username='dddd@tefffforg.com');
        insert u3;
        
        User u2 = new User(alias = 'test', email='ddd@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,title__c='Sales Rep',FunctionDepartment__c='Trade Sales',managerId=u3.Id,
        timezonesidkey='America/Los_Angeles', username='dddd@testorg.com');
        insert u2;
        
       
        System.runAs(u)
        {
                Sales_Target__c t=new Sales_Target__c(); 
                    t.Sales_Target_Type__c='In-Market Sales(RMB)'; 
                    t.Year__c='2010';
                    t.month__c='8';
                    t.SalesWeek1__c=0; 
                    t.SalesWeek2__c=0; 
                    t.SalesWeek3__c=0; 
                    t.SalesWeek4__c=0; 
                    t.SalesWeek5__c=0;
                    t.OwnerId=u3.Id;
                    insert t;
                    
            ss.SetTarget();
            List<Sales_Target__c> d=ss.TempTargetList;
            ss.Save();
            ss.OnchageAction();
        }
        System.runAs(u2)
        {
            ss.SetTarget();
            List<Sales_Target__c> d=ss.TempTargetList;
            ss.OnchageAction();
        }
        System.runAs(u3)
        {
                ss.SetTarget();
            List<Sales_Target__c> d=ss.TempTargetList;
            ss.Save();
            ss.OnchageAction();
        }
    }
}